<?php
namespace Ucmaim\Controller\Home;

class MemberController extends CommonController {

    public static $SESSION_NAME = 'member_info';

    public function _initialize(){
        parent::_initialize();
    }

    //会员中心
    public function Index(){
        $this->requireLogin();
        $uid = $this->member_info['uid'];
        $Order = D('Order');
        $waiting_to_pay = count($Order->get($uid, 'buyer', 1));
        $waiting_to_send = count($Order->get($uid, 'seller', 1));

        $this->assign('waiting', array('pay' => $waiting_to_pay, 'send' => $waiting_to_send));
        $this->display('Home/Member');
    }

    //买家订单列表
    public function MyOrderList(){
        $this->requireLogin();
        $uid = $this->member_info['uid'];
        $status = I('get.status', '', 'trim');
        $search = [];

        if( IS_POST ){
            $search_info = I('post.', '', 'trim');
            $status = $search_info['status'];
            if($search_info['order_sn']){
                $search['order_sn'] = $search_info['order_sn'];
                $this->assign('order_sn', $search_info['order_sn']);
            }

            if( $search_info['startDate'] && $search_info['endDate'] ){
                $start = strtotime($search_info['startDate']);
                $end   = strtotime($search_info['endDate']) + 86400;  //end需要加一天，防止当天的数据搜索不出来
                $search['order_time'] = array(array('EGT' , $start),array('ELT' , $end));
                $this->assign('startDate', $search_info['startDate']);
                $this->assign('endDate', $search_info['endDate']);
            }
        }else{
            $time = time();
            $this->assign('startDate', date('Y-m-d', $time - 2592000));
            $this->assign('endDate', date('Y-m-d', $time));
        }

        $status = '' === $status ? '' : (int)$status;
        $Order = D('Order');


        $list = $Order->get($uid, 'buyer', $status, $search);

        $list = gotoPage($list);
        $config = getConfig();
        $this->assign('config', $config);
        $this->assign('list', $list['data']);
        $this->assign('page', $list['page']);
        $this->assign('status', $status);
        $this->display();
    }

    //卖家订单列表
    public function SellerOrderList(){
        $this->requireLogin();
        $uid = $this->member_info['uid'];
        $status = I('get.status', '', 'trim');

        $search = [];

        if( IS_POST ){
            $search_info = I('post.', '', 'trim');
            $status = $search_info['status'];
            if($search_info['order_sn']){
                $search['order_sn'] = $search_info['order_sn'];
                $this->assign('order_sn', $search_info['order_sn']);
            }

            if( $search_info['startDate'] && $search_info['endDate'] ){
                $start = strtotime($search_info['startDate']);
                $end   = strtotime($search_info['endDate']) + 86400;  //end需要加一天，防止当天的数据搜索不出来
                $search['order_time'] = array(array('EGT' , $start),array('ELT' , $end));
                $this->assign('startDate', $search_info['startDate']);
                $this->assign('endDate', $search_info['endDate']);
            }
        }else{
            $time = time();
            $this->assign('startDate', date('Y-m-d', $time - 2592000));
            $this->assign('endDate', date('Y-m-d', $time));
        }

        $status = '' === $status ? '' : (int)$status;
        $Order = D('Order');
        $list = $Order->get($uid, 'seller', $status, $search);
        $list = gotoPage($list);
        $config = getConfig();
        $this->assign('config', $config);
        $this->assign('list', $list['data']);
        $this->assign('page', $list['page']);
        $this->assign('status', $status);
        $this->display();
    }

    // 出售中的商品
    public function MyGoods(){
        $this->requireLogin();
        $uid = $this->member_info['uid'];
        $Goods = D('Goods');
        $status = I('get.status', '', 'trim');
        $condition = [];
        $status = '' === $status ? '' : (int)$status;
        if(goods_status($status) === '') $status = '';
        if($status !== ''){
            $condition['goods_status'] = $status;
        }

        if( IS_POST ){
            $post = I('post.', '', 'trim');
            $relation = '';
            if( (int)$post['pid'] > 0 ){
                $relation .= (int)$post['pid'] . ',';
                if( (int)$post['gameid'] > 0 ){
                    $relation .= (int)$post['gameid'] . ',';
                    if( (int)$post['carrierid'] > 0 ){
                        $relation .= (int)$post['carrierid'] . ',';
                        if( (int)$post['groupid'] > 0 ){
                            $condition['A.gc_id'] = (int)$post['groupid'];
                        }
                    }
                }
            }

            if( '' !== $relation && ! $condition['A.gc_id']){
                $condition['C.gc_relation'] = array('LIKE', "$relation%");
            }elseif( '' !== $relation && $condition['A.gc_id'] ){
                $condition['A.gc_id'] = (int)$post['groupid'];
            }


            if( (int)$post['typeid'] > 0 ){
                $condition['A.goods_typeid'] = (int)$post['typeid'];
            }
            if( $post['startDate'] && $post['endDate'] ){
                $start = strtotime($post['startDate']);
                $end   = strtotime($post['endDate']) + 86400;  //end需要加一天，防止当天的数据搜索不出来
                $condition['goods_time'] = array(array('EGT' , $start),array('ELT' , $end));
                $this->assign('startDate', $post['startDate']);
                $this->assign('endDate', $post['endDate']);
            }
            if( $post['title'] ){
                $this->assign('title', $post['title']);
                $condition['A.goods_title'] = array('LIKE', "%{$post['title']}%");
            }
            $this->assign('selected', str_replace('###', 'select', $post['selected']));
        }else{
            $time = time();
            $this->assign('startDate', date('Y-m-d', $time - 2592000));
            $this->assign('endDate', date('Y-m-d', $time));
        }

        $result = $Goods->getSellerGoods($uid, $condition);
        $list = gotoPage($result);
        $category = D('GoodsCategory')->get(0, false);
        $this->assign('category', $category);
        $this->assign('list', $list['data']);
        $this->assign('page', $list['page']);
        $this->assign('status', $status);
        $this->display();
    }

    //下架商品
    public function SoldOut(){
        if(IS_GET){
            $this->requireLogin();
            $uid = $this->member_info['uid'];
            $gid=I('get.id');
            $Goods = D('Goods');
            $Goods->soldOut($uid,$gid);
            $this->redirect('Home/Member/MyGoods');
        }
    }

    // 交易明细
    public function TransRecords(){
        $search = [];
        $time = time();
        if( IS_POST ){
            $post = I('post.', '', 'trim');
            if( !empty($post['keyword']) ){
                $search['order_sn'] = $post['keyword'];
                $this->assign('keyword', $post['keyword']);
            }
            if( !empty($post['startDate']) && !empty($post['endDate']) ){
                $start = strtotime($post['startDate']);
                $end   = strtotime($post['endDate']) + 86400;  //end需要加一天，防止当天的数据搜索不出来
                $search['log_time'] = array(array('EGT' , $start),array('ELT' , $end));
                $this->assign('startDate', $post['startDate']);
                $this->assign('endDate', $post['endDate']);
            }
        }else{
            $this->assign('startDate', date('Y-m-d', $time - 2592000));
            $this->assign('endDate', date('Y-m-d', $time));
        }
        $this->requireLogin();
        $uid = $this->member_info['uid'];
        $Log = D('MoneyLog');
        $list = $Log->get($uid, $search);

        $list = gotoPage($list);
        $this->assign('list', $list['data']);
        $this->assign('page', $list['page']);
        $this->display();
    }

    //登陆
    public function Login(){
        if( IS_POST ){
            $post = I('post.', 'trim');
	        $name=$post['username'];
            //验证验证码
            if( ! $this->chkVerifyCode($post['img_valid']) ){
                $this->assign('error', true);
                $this->assign('error_text', '验证码不正确');
            }else{
                $password = md5($post['password']);
                $where = "(member_name='{$post['username']}' OR member_mobile='{$post['username']}') AND member_password = '$password'";
                $M = M('member');
                $result = $M->where($where)->find();
                if( empty($result) ){
                    $this->assign('error', true);
                    $this->assign('error_text', '账号或密码输入错误，请核对后重新输入');
                }elseif($result['member_status'] == 0 ) {
                    $this->assign('error', true);
                    $this->assign('error_text', '该账号已被禁用，请与管理员联系');
                }else{
                    //登陆成功
                    $this->_saveLoginInfo($result['member_id'], $result['member_name'], $result['member_mobile'], $result['member_qq'], $result['member_email']);
                    $ref = get_ref_url();
                    if( $ref !== '' ){
                        $this->redirect($ref);
                    }else{
                        $this->redirect('Home/Index');
                    }
                }
            }
        }
        $this->display('Home/Login');

    }

    //注销登陆
    public function Logout(){
        $this->requireLogin();
        $session = self::$SESSION_NAME;
        session($session, null);
        $this->redirect('Home/Member/Login');
    }

    //注册用户
    public function Register(){
        if( IS_POST ){
            $post = I('post.', 'trim');
            //验证手机号码格式
            if(! preg_match($this->mobile_preg, $post['user_tel'])){
                $this->error('注册手机号码格式不正确');
            };
            //验证验证码
            if( ! $this->chkVerifyCode($post['checkCode_tel']) ){
                $this->error('验证码不正确');
            }
            //验证手机验证码
            if( ! $this->chkSMSCode($post['user_tel'], $post['user_verificationcode']) ){
                $this->error('手机验证码不正确');
            }

            // 防止重复提交
            compare_form_hash($post['hash']);
            $M = M('member');
            $data['member_password'] = md5($post['user_userPassword']);
            $data['member_time']     = time();
            $data['member_mobile']   = $post['user_tel'];
            $data['member_status']   = 1;

            if($M->create($data)){
                $M->add();
                $uid = $M->getLastInsID();
                $this->_saveLoginInfo($uid, '', $data['member_mobile'], '', '');
                $this->redirect('Home/Index');
            }else{
                $this->error('注册失败，请稍候再试');
            }

        }else{
            $hash = form_hash();
            // 获取服务协议内容
            $title = '游戏卖服务协议';
            $cid = D('ContentCategory')->getCategoryList(0, 'agreement')[0]['id'];
            if( $cid ){
                $map['title'] = $title;
                $agreement = D('Content')->where($map)->getList()[0];
            }else{
                $agreement = [];
            }
            $this->assign('agreement', $agreement);
            $this->assign('hash', $hash);
            $this->display('Home/Register');
        }

    }

    // 保存登陆信息
    private function _saveLoginInfo($uid, $nickname, $mobile, $qq, $email){
        $session_name = self::$SESSION_NAME;
        session($session_name, array(
            'uid'      => $uid,
            'nickname' => $nickname ? $nickname : $mobile,
            'mobile'   => $mobile,
            'qq'       => $qq,
            'email'    => $email,
        ));
    }

    //修改密码
    public function Passphrases(){
        $this->requireLogin();
        if( IS_GET ){
            $this->display();
        }else{
            $img_valid=I('post.img_valid');
            if( ! $this->chkVerifyCode($img_valid) ){
                $this->error('验证码不正确');
            }
            $member=M('member');
            $rules = array(
                array('oldPassword','require','当前密码必须填写！'),
                array('member_newpassword','require','密码必须填写！'),
                array('member_password','require','确认密码必须填写！'),
                array('member_password','member_newpassword','确认密码不正确！',0,'confirm'),
                array('member_password','6,20','密码长度必须6-20位！',3,'length'),
            );
            if (!$member->validate($rules)->create()){
                exit($member->getError());
            }
            $uid=$this->member_info['uid'];
            $map['member_id'] = $uid;
            $mark=$member->where($map)->find();
            $tablepass=$mark['member_password'];
            $oldpass=md5(I('post.oldPassword'));
            if($tablepass!=$oldpass){
                $this->error('当前密码不正确');
            }
            $newpass=md5(I('post.member_password'));
            if($newpass==$oldpass){
                $this->error('新密码不能和旧密码相同');
            }
            $data['member_password']=$newpass;
            $info=$member->where("member_id=$uid")->save($data);
            if($info){
                $session = self::$SESSION_NAME;
                session($session, null);
                $this->success('修改成功', U('Home/Member/Login'));
            }else{
                $this->error('修改失败');
            }
        }

    }

    public function ForgetPassword(){
        if( !empty($this->member_info) ) $this->redirect('Home/Member/Index');
        $process = session('FindPassProcess');
        $post = I('post.', '', 'trim');
        $step = (int)$post['step'];
        switch($step){
            default:
            case 1:
                // 第一步 构造过程
                $process = array(
                    'step' => 1,
                    'tel'  => '',
                    'code' => false,
                    'smscode' => false,
                );
                session('FindPassProcess' , $process);
                break;
            case 2:
                if(! session('FindPassProcess')) $this->error('非法操作');
                // 检验验证码
                if( true === $process['code'] || $this->chkVerifyCode($post['code'])){
                    $process['step'] = 2;
                    $process['code'] = true;
                }else{
                    $this->error('验证码不正确');
                }
                // 检测手机号码格式
                if( ! $process['tel'] ){
                    if( ! preg_match($this->mobile_preg, $post['tel']) ) $this->error('您输入的手机号码格式不正确，请检查手机号码');
                    // 检测手机号码是否已存在
                    if( !$this->isExistMobile($post['tel']) ) $this->error('此手机号码没有绑定账号');
                    // 发送手机验证码
                    $content = '您的认证码是： {$code}。请不要把认证码泄露给其他人。如非本人操作，可不用理会！';
                    $result  = $this->sendSMSCode($post['tel'], $content);
                    if($result['code'] !== 0) $this->error('短信验证码发送不成功，请稍候再操作');
                    $process['tel'] = $post['tel'];
                    session('FindPassProcess', $process);
                    if( C('APP_DEBUG') ){
                        $this->assign('debug_info', $result['debug']);
                    }
                }
                $this->assign('tel', $post['tel']);
                break;
            case 3:
                // 验证短信验证码
                if( !$process['smscode'] ){
                    if($this->chkSMSCode($process['tel'], $post['smscode'])){
                        $process['smscode'] = true;
                        session('FindPassProcess', $process);
                    }else{
                        $this->error('手机短信验证码不正确');
                    }
                }
                break;
            case 4:
                // 修改密码
                if( $post['password_confirm'] !== $post['password'] ){
                    $this->error('两次输入密码不相同，请重新输入');
                }
                $Member = D('Member');
                $result = $Member->updateMemberPassByMobile($process['tel'], $post['password']);
                session('FindPassProcess', null);
                $result ? $this->success('已成功重置您的密码', U('Home/Member/Login')) : $this->error('重置密码失败，请稍候再试', U('Home/Member/ForgetPassword'));
                exit;
                break;
        }
        $this->assign('step', $step <= 0 ? 1 : $step);
        $this->assign('next', $step + 1);
        $this->display();
    }

    //账号资料修改
    public function EditMemberInfo(){
        $this->requireLogin();
        $uid = $this->member_info['uid'];
        $Member = D('Member');
        if( IS_POST ){
            $post = I('post.', '', 'trim');
            if( $uid !== $post['uid'] ) $this->error('非法操作', U('Home/Member/EditMemberInfo'));
            if( '' !== $post['member_name'] && null !== $post['member_name'] ){
                $e = $Member->isExist('member_name', $post['member_name'], $uid);
                if( $e ) $this->error('此用户名已被占用', U('Home/Member/EditMemberInfo'));
                $data['member_name'] = $post['member_name'];
            }
            $e = $Member->isExist('member_email', $post['member_email'], $uid);
            if( $e ) $this->error('此邮箱地址已被占用', U('Home/Member/EditMemberInfo'));
            $data['member_email'] = $post['member_email'];
            $data['member_qq'] = $post['member_qq'];
            $result = $Member->updateUser($uid, $data);
            if( $result ){
                $member_info = $Member->memberInfo($uid);
                $this->_saveLoginInfo($uid, $member_info['member_name'], $member_info['member_mobile'], $member_info['member_qq'], $member_info['member_email']);
                $this->assign('alert', '更新成功');
            }else{
                $this->assign('alert', '更新失败');
            }
        }

        // 读取数据库中会员信息
        $member_info = $Member->memberInfo($uid);
        $this->assign('member', $member_info);
        $this->display();
    }
}
